package com.wen.system.shiro.filter;

import cn.hutool.json.JSONUtil;
import com.wen.common.exception.CustomException;
import com.wen.common.utils.JwtUtil;
import com.wen.common.utils.ResponseResult;
import com.wen.system.jwt.JwtToken;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.util.AntPathMatcher;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
//@Component
public class JwtFilter extends BasicHttpAuthenticationFilter {

    @Autowired
    JwtUtil jwtUtil;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    // 登录标识
    private static final String LOGIN_SIGN = "token";

    @Override
    protected String getAuthzHeader(ServletRequest request) {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        return httpRequest.getHeader(LOGIN_SIGN);
    }

    /**
     * 是否需要认证
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String authzHeader = this.getAuthzHeader(request);
        return authzHeader != null;
//        if (antPathMatcher.match("/doLogin", req.getRequestURI())) {
//
//            return true;
//        }
//        return false;
    }

    /**
     * 1. 返回true，shiro就直接允许访问url
     * 2. 返回false，shiro才会根据onAccessDenied的方法的返回值决定是否允许访问url
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("isAccessAllowed 方法被调用");
        // 有token就去认证
        if (isLoginAttempt(request, response)) {
            //进行Realm认证
            try {
                executeLogin(request, response);
            }catch (UnknownAccountException e){
                log.info("用户账户找不到");
                return false;
            }catch (NullPointerException e){
                log.info("认证异常");
                return false;
            }catch (CustomException e){
                log.info("我的异常");
                return false;
            } catch (Exception e) {
                //token 错误 认证失败到访问失败方法
//                responseError(response, e.getMessage());
                log.info("realm里面异常了 ,message={}", e.getClass());
//                e.printStackTrace();

                return false;
            }
        }
        // 没有就放行 ，说明是游客，或者访问登录页面
        return true;
    }

    /**
     * 重写AuthenticatingFilter的executeLogin方法丶执行登陆操作
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        // 校验jwt
        String token = this.getAuthzHeader(request);//Access-Token
        Claims claim = jwtUtil.getClaimByJwt(token);
        if (claim == null || jwtUtil.isExpired(claim.getExpiration())) {
            throw new CustomException("666","token已失效，请重新登录");
        }

        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行认证,如果错误他会抛出异常并被捕获,如果没有抛出异常则代表认证成功，返回true
        log.info("过滤器生效，去执行login认证");
        getSubject(request, response).login(jwtToken);
        return true;
    }

    /**
     * 将非法请求跳转到 /unauthorized/**
     */
    private void responseError(ServletResponse response, String message) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //设置编码，否则中文字符在重定向时会变为空字符串
        try {
            message = URLEncoder.encode(message, "UTF-8");
            System.out.println(message);
            httpServletResponse.sendRedirect("/unauthorized/" + message);
        } catch (Exception e) {
            log.info("responseError执行了");
        }
    }

    /**
     * 访问失败处理
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        // 重定向到login
        HttpServletResponse res = (HttpServletResponse) response;
        res.setCharacterEncoding("UTF-8");
        ResponseResult responseResult = ResponseResult.error("401", "token异常,重定向到login");
        log.info("token异常code:[{}],msg:[{}]", responseResult.getCode(), responseResult.getMsg());
        String json = JSONUtil.toJsonStr(responseResult);
//
        try {
            res.getWriter().print(json);
        } catch (IOException ioException) {
        }
        return false;
/*        String jwt = this.getAuthzHeader(request);
        if (StrUtil.isEmpty(jwt)) {
            // jwt 为空，放行，访问接口
            return true;
//            throw new MyException("111","token为空！");
        } else {

            // 校验jwt
            Claims claim = jwtUtils.getClaimByToken(jwt);
            if (claim == null || jwtUtils.isTokenExpired(claim.getExpiration())) {
                throw new ExpiredCredentialsException("token已失效，请重新登录");
                // 异常转发到Controller层,由全局异常捕获 ，（后期是否有更好的解决方法）
//                req.setAttribute("token.error", new MyException("401", "用户登录已过期"));
//                req.getRequestDispatcher("/error/exthrow").forward(request, response);
            }
            System.out.println("=============token规范==========");
            // 执行登录 --> 去创建我们的jwtToken
            return executeLogin(request, response);
        }*/
    }

    /**
     * 认证失败处理
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        ResponseResult responseResult = ResponseResult.error("111111", "onLoginFailure方法执行了");
//
//        Throwable throwable = e.getCause() == null ? e : e.getCause();
//        Result result = Result.error("0001", throwable.getMessage());
        String json = JSONUtil.toJsonStr(responseResult);
//
        try {
            httpServletResponse.getWriter().print(json);
        } catch (IOException ioException) {
        }
        return false;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        //添加可以返回自定义header信息
        httpServletResponse.setHeader("Access-Control-Expose-Headers", LOGIN_SIGN);
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

}
